package com.chinaoryx.dwr;

import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BasicDynaClass;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.ConvertUtilsBean;
import org.apache.commons.beanutils.DynaBean;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.dom4j.DocumentException;

public class QueryServlet extends HttpServlet {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(QueryServlet.class);

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String sqlName = request.getParameter("sqlName");
		Map<String, Object> sqlParamMap = new HashMap<String, Object>();

		Enumeration<String> enu = request.getParameterNames();

		try {

			while (enu.hasMoreElements()) {
				String str = enu.nextElement();
				if (str.startsWith("param_")) {
					String name = str.substring(6);
					String paramValue = request.getParameter(str);
					if (paramValue != null && !"".equals(paramValue)) {
						String javaTypeClassName = request
								.getParameter("javaType_" + name);
						// dynaBean.set(name, paramValue);
						Object value;

						value = ConvertUtils.convert(paramValue,
								Class.forName(javaTypeClassName));

						sqlParamMap.put(name, value);
					}

				}
			}

			Writer out = response.getWriter();

			out.write(sqlParamMap.toString());

			String resource = "Configuration.xml";
			Reader reader = Resources.getResourceAsReader(resource);
			SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder()
					.build(reader);
			SqlSession sqlSession = sqlMapper.openSession();
			out.write("<table border='1'>");
			sqlSession.select(sqlName, sqlParamMap,
					new CommonResultHandler(out));
			out.write("</table>");

			sqlSession.close();
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}

}
